package com.hsl.housaileibot001.utils;

import com.alibaba.excel.EasyExcel;
import com.hsl.housaileibot001.handle.CustomCellWriteHandler;
import com.hsl.housaileibot001.handle.DateConverter;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Excel导入导出工具类
 * 基于EasyExcel封装常用操作
 */
@Slf4j
public class ExcelUtil {
    private static final String CONTENT_TYPE = "application/vnd.ms-excel";
    private static final String ENCODING = "utf-8";
    private static final String CONTENT = "Content-Disposition";
    private static final String ATTACHMENT = "attachment;filename=";

    /**
     * 导出Excel
     */
    public static void exportExcel(HttpServletResponse response, List<?> list, Class<?> o, String fileName, String sheetName) throws IOException {
        response.setContentType(CONTENT_TYPE);
        response.setCharacterEncoding(ENCODING);

        fileName = String.format("%s_%s.xlsx", fileName, System.currentTimeMillis());
        // 对文件名进行URL编码
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader(CONTENT, ATTACHMENT + encodedFileName);
        // 这里 需要指定写用哪个class去写
        EasyExcel.write(response.getOutputStream(), o).autoCloseStream(Boolean.FALSE)
                .registerWriteHandler(new CustomCellWriteHandler())
                .registerConverter(new DateConverter())
                .sheet(sheetName)
                .doWrite(list);
    }

    /**
     * 导入Excel
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<T> clazz) throws IOException {
        if (!isExcelFile(file)) {
            throw new IllegalArgumentException("文件不是有效的Excel文件");
        }

        try {
            return EasyExcel.read(file.getInputStream())
                    .head(clazz)
                    .sheet()
                    .doReadSync();
        } catch (Exception e) {
                throw new IOException("Excel文件读取失败: " + e.getMessage(), e);
        }
    }


    /**
     * 验证文件是否为Excel文件
     *
     * @param file 上传的文件
     * @return 是否为Excel文件
     */
    public static boolean isExcelFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }

        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return false;
        }

        String extension = originalFilename.toLowerCase();
        return extension.endsWith(".xlsx") || extension.endsWith(".xls");
    }
}
